import { createStore } from 'redux'

// 创建store数据仓库
let userInfo = localStorage.getItem('userInfo')
try {
	userInfo = JSON.parse(userInfo) || {}
} catch (err) {
	userInfo = {}
}

const state = {
	userInfo,
}

// reducer: 修改State的方法（在reuducer内部不修改传入的参数）
const reducer = function (state, action) {
	console.log('reducer.action=', action)
	let newState = state
	switch (action.type) {
		// store.dispatch({type:'login',payload})
		case 'login':
			newState = {
				userInfo: action.payload,
			}
			// 更新本地存储数据
			localStorage.setItem('userInfo', JSON.stringify(action.payload))
			return newState
		// store.dispatch({type:'logout'})
		case 'logout':
			newState = {
				userInfo: {},
			}
			localStorage.removeItem('userInfo')
			return newState
		default:
			return newState
	}
}

// 创建store数据仓库
const store = createStore(reducer, state)
console.log('store', store)

// 监听操作
store.subscribe(function () {
	// 这里的代码在State被修改后执行
	console.log('subscribe', store.getState())
})

export default store
